package cn.iocoder.an.module.mold.service.upkeepcategory;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.an.module.mold.controller.admin.category.vo.CategoryImportExcelVO;
import cn.iocoder.an.module.mold.dal.dataobject.category.CategoryDO;
import cn.iocoder.an.module.mold.utils.ImportRespVO;
import io.micrometer.common.util.StringUtils;
import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;

import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

import cn.iocoder.an.module.mold.controller.admin.upkeepcategory.vo.*;
import cn.iocoder.an.module.mold.dal.dataobject.upkeepcategory.UpkeepCategoryDO;
import cn.iocoder.an.framework.common.pojo.PageResult;
import cn.iocoder.an.framework.common.util.object.BeanUtils;

import cn.iocoder.an.module.mold.dal.mysql.upkeepcategory.UpkeepCategoryMapper;

import static cn.iocoder.an.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.an.module.mold.enums.ErrorCodeConstants.*;

/**
 * 保养类型 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
public class UpkeepCategoryServiceImpl implements UpkeepCategoryService {

    @Resource
    private UpkeepCategoryMapper upkeepCategoryMapper;

    @Override
    public Long createUpkeepCategory(UpkeepCategorySaveReqVO createReqVO) {
        // 插入
        UpkeepCategoryDO upkeepCategory = BeanUtils.toBean(createReqVO, UpkeepCategoryDO.class);
        upkeepCategoryMapper.insert(upkeepCategory);

        // 返回
        return upkeepCategory.getId();
    }

    @Override
    public void updateUpkeepCategory(UpkeepCategorySaveReqVO updateReqVO) {
        // 校验存在
        validateUpkeepCategoryExists(updateReqVO.getId());
        // 更新
        UpkeepCategoryDO updateObj = BeanUtils.toBean(updateReqVO, UpkeepCategoryDO.class);
        upkeepCategoryMapper.updateById(updateObj);
    }

    @Override
    public void deleteUpkeepCategory(Long id) {
        // 校验存在
        validateUpkeepCategoryExists(id);
        // 删除
        upkeepCategoryMapper.deleteById(id);
    }

    @Override
    public void deleteUpkeepCategoryListByIds(List<Long> ids) {
        // 删除
        upkeepCategoryMapper.deleteByIds(ids);
    }


    private void validateUpkeepCategoryExists(Long id) {
        if (upkeepCategoryMapper.selectById(id) == null) {
            throw exception(UPKEEP_CATEGORY_NOT_EXISTS);
        }
    }

    @Override
    public UpkeepCategoryDO getUpkeepCategory(Long id) {
        return upkeepCategoryMapper.selectById(id);
    }


    @Override
    public List<UpkeepCategoryDO> getUpkeepCategoryAll() {
        return upkeepCategoryMapper.selectList();
    }

    @Override
    public PageResult<UpkeepCategoryDO> getUpkeepCategoryPage(UpkeepCategoryPageReqVO pageReqVO) {
        return upkeepCategoryMapper.selectPage(pageReqVO);
    }

    @Override
    public Long getUpkeepCategoryIdByCode(String code) {
        UpkeepCategoryDO categoryDO = upkeepCategoryMapper.selectFirstOne(UpkeepCategoryDO::getCode, code);
        if (categoryDO != null) {
            return categoryDO.getId();
        } else {
            throw exception(UPKEEP_CATEGORY_NOT_EXISTS);
        }
    }

    @Override
    public ImportRespVO importUpkeepCategoryList(List<UpkeepCategoryImportExcelVO> iomportCategory, boolean isUpdateSupport) {
        if (CollUtil.isEmpty(iomportCategory)) {
            throw exception(UPKEEP_CATEGORY_NOT_EXISTS);
        }

        ImportRespVO respVO = ImportRespVO.builder().insertNameList(new ArrayList<>())
                .updateNameList(new ArrayList<>()).failureMap(new LinkedHashMap<>()).build();

        AtomicInteger count = new AtomicInteger(1);

        iomportCategory.forEach(item -> {
            count.incrementAndGet();//记录行号
            // 2.1.1 校验编码
            if (StringUtils.isEmpty(item.getCode())) {
                return;
            }
            // 2.1.2 校验名称
            if (StringUtils.isEmpty(item.getName())) {
                respVO.getFailureMap().put(item.getCode(), "名称不能为空!");
                return;
            }
            //更新或者插入
            //判断图号是否重复
            String code = item.getCode();
            UpkeepCategoryDO exists = upkeepCategoryMapper.selectFirstOne(
                    UpkeepCategoryDO::getCode, code
            );

            if (exists != null) {
                if (isUpdateSupport) {
                    //允许更新
                    //设置ID
                    item.setId(exists.getId());
                    UpkeepCategoryDO categoryDO = BeanUtils.toBean(item, UpkeepCategoryDO.class);
                    upkeepCategoryMapper.updateById(categoryDO);
                    respVO.getUpdateNameList().add(item.getCode());
                } else {
                    respVO.getFailureMap().put(item.getCode(), UPKEEP_CATEGORY_NAME_DUPLICATE.getMsg());
                }
            } else {
                upkeepCategoryMapper.insert(BeanUtils.toBean(item, UpkeepCategoryDO.class));
                respVO.getInsertNameList().add(item.getCode());
            }
        });
        return respVO;
    }
}